package com.lyn.view.surface;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.lyn.module_custom_utils.bitmap.BitmapConversionUtil;
import com.lyn.view.R;

/**
 * created by lyn at 2021/11/2
 */
public class ShowRGBSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private Context context;
    private SurfaceHolder holder;
    private Thread thread;
    private volatile boolean isTag = true;
    private Bitmap bitmap;
    private Paint paint;

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public ShowRGBSurfaceView(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public ShowRGBSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }


    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        holder = this.getHolder();
        holder.addCallback(this);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        thread = new Thread(this);
        thread.start();
        isTag = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isTag = false;
    }

    @Override
    public void run() {
        while (isTag) {
            Canvas canvas = null;
            try {
                if (holder == null) continue;
                canvas = holder.lockCanvas();
                canvas.drawRGB(255, 255, 255);
                if (bitmap == null) {
                    Bitmap promptBitmap = BitmapConversionUtil.drawableToBitmap(context.getDrawable(R.drawable.camera));
                    canvas.drawBitmap(promptBitmap
                            , null
                            , new RectF(canvas.getWidth() / 2 - 100, canvas.getHeight() / 2 - 100, canvas.getWidth() / 2 + 100, canvas.getHeight() / 2 + 100)
                            , paint);
                } else {
                    canvas.drawBitmap(bitmap
                            , null
                            , new RectF(0, 0, canvas.getWidth(), canvas.getHeight())
                            , paint);

                }
            } finally {
                if (canvas == null) continue;
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }
}
